<?php
class SingpostContract {
    var $date;
    var $description;
}

class Uuch_Track_SingpostAPI{
    public $url;
    public $body;
    public function __construct($url) {
        $this->url = $url;
        $client = new Zend_Http_Client();
        $client->setEncType('');
        $client->setUri($this->url);
        $response = $client->request();
        $this->body = $response->getBody();
    }
    
    public function query(){
        error_reporting(NULL);
        ini_set('display_errors','Off');
        $seletpreg = '%<table width=\"100\%\" cellspacing=\"2\" cellpadding=\"2\" bordercolor=\"#CCCCCC\" border=\"1\" style=\"BORDER-COLLAPSE: collapse\" class=\"commonTable\">(.*?)</table>%si';
        $match = array();        
        preg_match_all($seletpreg, $this->body, $match);        
        $resultArray = $this->getArray($match[0][0]);
        unset($resultArray[0]);
        $resultList = array();        
        foreach ($resultArray as $value) {
            $model = new SingpostContract();
            $model->date = trim($value[0]);
            $model->description = trim($value[1]);
            array_push($resultList, $model);
        }
        return $resultList;                
    }
    
    private function getArray($table) {
        $table = preg_replace("'<table[^>]*?>'si", "", $table);
        $table = preg_replace("'<tr[^>]*?>'si", "", $table);
        $table = preg_replace("'<td[^>]*?>'si", "", $table);
        $table = str_replace("</tr>", "{tr}", $table);
        $table = str_replace("</td>", "{td}", $table);
        //去掉 HTML 标记
        $table = preg_replace("'<[\/\!]*?[^<>]*?>'si", "", $table);
        //去掉空白字符 
        $table = preg_replace("'([\r\n])[\s]+'", "", $table);
        // $table = str_replace(" ", "", $table);
        // $table = str_replace(" ", "", $table);
        $table = explode('{tr}', $table);
        array_pop($table);
        foreach ($table as $key => $tr) {
            $td = explode('{td}', $tr);
            array_pop($td);
            $td_array[] = $td;
        }
        return $td_array;
    }
    
}

?>